import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/utils/file_util.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/api/file_upload_apis.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';

///特殊作业-自文件上传样式控件
///[title] 标题
///[onCallBack] 选择回调
///[uploadedFiles] 已上传的文件列表
///[isRequired] 是否必填
///[hintText] 提示文字
///[isEnabled] 是否可编辑
///[isShowDivider] 是否显示分割线
///[isChange] 是否在交接班中
class CustomFileUploadPage extends StatefulWidget {
  const CustomFileUploadPage({
    required this.title,
    required this.onCallBack,
    this.uploadedFiles,
    this.isRequired = true,
    super.key,
    this.hintText,
    this.isEnabled = true,
    this.isShowDivider = true,
    this.isChange = false,
  });

  final String title;
  final Function(List<String>) onCallBack;
  final List<String>? uploadedFiles;
  final bool isRequired;
  final String? hintText;
  final bool isEnabled;
  final bool isShowDivider;
  final bool isChange;

  @override
  State<CustomFileUploadPage> createState() => _CustomFileUploadPageState();
}

class _CustomFileUploadPageState extends State<CustomFileUploadPage> {
  List<String> fileUrlList = [];

  @override
  initState() {
    super.initState();
    _initDate();
  }

  /// 初始化数据
  void _initDate() {
    if (widget.uploadedFiles != null && widget.uploadedFiles!.isNotEmpty) {
      fileUrlList.addAll(widget.uploadedFiles!);
    }
  }

  /// 拍摄图片
  void _takePictures() async {
    final ImagePicker picker = ImagePicker();

    // 拍摄图片
    final XFile? image =
        await picker.pickImage(source: ImageSource.camera, imageQuality: 30);
    if (image != null) {
      final images = await FileUploadApis.uploadFile(
          fileUrl: image.path,
          fileName: '${DateTime.now().millisecondsSinceEpoch}.jpg');
      if (images != '') {
        fileUrlList.add(images);
        //进行回调
        widget.onCallBack(fileUrlList);
        setState(() {});
      } else {
        AppToast.showWarning('上传失败');
      }
    } else {
      // AppToast.showWarning('未选择图片');
    }
  }

  /// 选择文件
  void _selectFile() async {
    final result = await FilePicker.platform.pickFiles(
        // type FileType.custom,
        // allowedExtensions ['pdf', 'doc'],
        // allowMultiple true
        );
    if (result != null) {
      final PlatformFile platformFile = result.files.first;
      final file = await FileUploadApis.uploadFile(fileUrl: platformFile.path!);
      if (file != '') {
        fileUrlList.add(file);
        //进行回调
        widget.onCallBack(fileUrlList);
        setState(() {});
      } else {
        AppToast.showWarning('上传失败');
      }
    } else {
      // AppToast.showWarning('未选择文件');
    }
  }

  ///获取文件列显示
  Widget _getFileView(String url) {
    //本地文件名
    final String currUrlName = url.toString().substring(25);
    //.符号的坐标
    // final int finishIndex = currUrlName.indexOf('.');
    // if (finishIndex == -1) {
    //   return Container();
    // }
    // currUrlName = currUrlName.toString().substring(0, finishIndex);
    return Row(
      children: [
        Expanded(
            child: Text(
          currUrlName,
          style: TextStyle(
            fontSize: 13.sp,
            color: const Color(0xFF5C6DFF),
          ),
        ).clickOnce(() {
          //打开文件
          FileUtils.openFile(Interface.fileUrl + url);
        })),
        Visibility(
            visible: widget.isEnabled && !widget.isChange,
            child: Container(
              alignment: Alignment.center,
              child: const Icon(
                Icons.highlight_remove,
                color: Color(0xFFFD6B6B),
              ),
            ).clickOnce(() {
              setState(() {
                fileUrlList.remove(url);
                widget.onCallBack(fileUrlList);
              });
            }))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Visibility(
                visible: widget.isRequired,
                child: Text(
                  '*',
                  style: TextStyle(
                    fontSize: 14.sp,
                    height: 1.2,
                    color: AppColors.meaning_color_danger,
                  ),
                )),
            Text(
              widget.title,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.1,
                color: AppColors.font_color_black,
              ),
            ),
            AppGaps.hGap20,
            Expanded(
              child: SizedBox(
                height: 50.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      widget.isEnabled
                          ? widget.hintText ?? '请上传'
                          : fileUrlList.isEmpty
                              ? '暂无'
                              : '',
                      style: TextStyle(
                        fontSize: 14.sp,
                        height: 1.2,
                        color: AppColors.text_grey,
                      ),
                    ),
                    Visibility(
                        visible: widget.isEnabled,
                        child: Row(
                          children: [
                            AppGaps.hGap6,
                            Icon(Icons.arrow_forward_ios,
                                size: 14.sp, color: AppColors.text_grey)
                          ],
                        )),
                  ],
                ),
              ).clickOnce(() {
                if (!widget.isEnabled) {
                  return;
                }
                showCupertinoModalPopup(
                  context: context,
                  builder: (context) {
                    return CupertinoActionSheet(
                      actions: [
                        CupertinoActionSheetAction(
                          child: const Text('拍照'),
                          onPressed: () {
                            Navigator.of(context).pop();
                            _takePictures();
                          },
                        ),
                        CupertinoActionSheetAction(
                          child: const Text('从手机中选择'),
                          onPressed: () {
                            Navigator.of(context).pop();
                            _selectFile();
                          },
                        ),
                      ],
                      cancelButton: CupertinoActionSheetAction(
                        onPressed: Navigator.of(context).pop,
                        child: const Text('取消'),
                      ),
                    );
                  },
                );
              }),
            ),
          ],
        ),
        ListView.separated(
          itemCount: fileUrlList.length,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _getFileView(fileUrlList[index]);
          },
          separatorBuilder: (BuildContext context, int index) {
            return AppGaps.vGap8;
          },
        ),
        Visibility(visible: fileUrlList.isNotEmpty, child: AppGaps.vGap10),
        Visibility(
            visible: widget.isShowDivider,
            child: Divider(
              height: 1.w,
              color: AppColors.bg_color_grey,
            )),
      ],
    );
  }
}
